package com.zhitan.ems.alarm.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhitan.ems.alarm.entity.AlarmRecordsEntity;
import com.zhitan.ems.alarm.enums.ALARTM_STATUS_ENUM;
import com.zhitan.ems.alarm.mapper.AlarmRecordsMapper;
import com.zhitan.ems.alarm.service.AlarmRecordsService;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.enums.DEVICE_ONLINE_STATUS_ENUM;
import com.zhitan.ems.app.stat.vo.StatisticsPieVO;
import com.zhitan.ems.common.extra.utils.DateUtil;
import com.zhitan.ems.framework.core.mp.base.BaseServiceImpl;
import com.zhitan.ems.framework.core.vo.VQueryKit;

@Service
public class AlarmRecordsServiceImpl extends BaseServiceImpl<AlarmRecordsMapper, AlarmRecordsEntity> implements AlarmRecordsService {
    
    @Override
    public Map<String, Object> getAlarmStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取今天的开始和结束时间
        Date today = new Date();
        Date startOfToday =  DateUtil.getStartOfDate(today);
        Date endOfToday =  DateUtil.getEndOfDate(today);
        
        // 获取昨天的开始和结束时间
        Date yesterday =  DateUtil.addDays(today, -1);
        Date startOfYesterday =  DateUtil.getStartOfDate(yesterday);
        Date endOfYesterday =  DateUtil.getEndOfDate(yesterday);
        
        // 今日报警数量
        QueryWrapper<AlarmRecordsEntity> todayAlarmQuery = new QueryWrapper<>();
        todayAlarmQuery.between("alarm_time", startOfToday, endOfToday);
        int todayAlarmCount = Math.toIntExact(baseMapper.selectCount(todayAlarmQuery));
        
        // 今日解决数量 (状态为已解决的报警)
        QueryWrapper<AlarmRecordsEntity> todayResolvedQuery = new QueryWrapper<>();
        todayResolvedQuery.between("alarm_time", startOfToday, endOfToday);
        todayResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int todayResolvedCount = Math.toIntExact(baseMapper.selectCount(todayResolvedQuery));
        
        // 昨日报警数量
        QueryWrapper<AlarmRecordsEntity> yesterdayAlarmQuery = new QueryWrapper<>();
        yesterdayAlarmQuery.between("alarm_time", startOfYesterday, endOfYesterday);
        int yesterdayAlarmCount = Math.toIntExact(baseMapper.selectCount(yesterdayAlarmQuery));
        
        // 昨日解决数量
        QueryWrapper<AlarmRecordsEntity> yesterdayResolvedQuery = new QueryWrapper<>();
        yesterdayResolvedQuery.between("alarm_time", startOfYesterday, endOfYesterday);
        yesterdayResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int yesterdayResolvedCount = Math.toIntExact(baseMapper.selectCount(yesterdayResolvedQuery));
        
        // 计算报警环比增长率
        double alarmChainGrowthRate = 0.0;
        if (yesterdayAlarmCount != 0) {
            alarmChainGrowthRate = ((double)(todayAlarmCount - yesterdayAlarmCount) / yesterdayAlarmCount) * 100;
        }
        
        // 将结果放入Map
        result.put("currentAlarmCount", todayAlarmCount);
        result.put("currentResolvedCount", todayResolvedCount);
        result.put("lastAlarmCount", yesterdayAlarmCount);
        result.put("lastResolvedCount", yesterdayResolvedCount);
        result.put("alarmChainGrowthRate", String.format("%.2f%%", alarmChainGrowthRate));
        result.put("current",  DateUtil.formatDate(startOfToday, "yyyy-MM-dd"));
        result.put("last",  DateUtil.formatDate(startOfYesterday, "yyyy-MM-dd"));
        
        return result;
    }
    
    @Override
    public Map<String, Object> getMonthlyAlarmStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前月份的开始和结束时间
        Date today = new Date();
        Date startOfCurrentMonth =  DateUtil.getStartOfMonth(today);
        Date endOfCurrentMonth =  DateUtil.getEndOfMonth(today);
        
        // 获取上个月的开始和结束时间
        Date lastMonth =  DateUtil.addMonths(today, -1);
        Date startOfLastMonth =  DateUtil.getStartOfMonth(lastMonth);
        Date endOfLastMonth =  DateUtil.getEndOfMonth(lastMonth);
        
        // 当月报警数量
        QueryWrapper<AlarmRecordsEntity> currentMonthAlarmQuery = new QueryWrapper<>();
        currentMonthAlarmQuery.between("alarm_time", startOfCurrentMonth, endOfCurrentMonth);
        int currentMonthAlarmCount = Math.toIntExact(baseMapper.selectCount(currentMonthAlarmQuery));
        
        // 当月解决数量
        QueryWrapper<AlarmRecordsEntity> currentMonthResolvedQuery = new QueryWrapper<>();
        currentMonthResolvedQuery.between("alarm_time", startOfCurrentMonth, endOfCurrentMonth);
        currentMonthResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int currentMonthResolvedCount = Math.toIntExact(baseMapper.selectCount(currentMonthResolvedQuery));
        
        // 上月报警数量
        QueryWrapper<AlarmRecordsEntity> lastMonthAlarmQuery = new QueryWrapper<>();
        lastMonthAlarmQuery.between("alarm_time", startOfLastMonth, endOfLastMonth);
        int lastMonthAlarmCount = Math.toIntExact(baseMapper.selectCount(lastMonthAlarmQuery));
        
        // 上月解决数量
        QueryWrapper<AlarmRecordsEntity> lastMonthResolvedQuery = new QueryWrapper<>();
        lastMonthResolvedQuery.between("alarm_time", startOfLastMonth, endOfLastMonth);
        lastMonthResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int lastMonthResolvedCount = Math.toIntExact(baseMapper.selectCount(lastMonthResolvedQuery));
        
        // 计算月度报警环比增长率
        double monthlyAlarmChainGrowthRate = 0.0;
        if (lastMonthAlarmCount != 0) {
            monthlyAlarmChainGrowthRate = ((double)(currentMonthAlarmCount - lastMonthAlarmCount) / lastMonthAlarmCount) * 100;
        }
        
        // 将结果放入Map
        result.put("currentAlarmCount", currentMonthAlarmCount);
        result.put("currentResolvedCount", currentMonthResolvedCount);
        result.put("lastAlarmCount", lastMonthAlarmCount);
        result.put("lastResolvedCount", lastMonthResolvedCount);
        result.put("alarmChainGrowthRate", String.format("%.2f%%", monthlyAlarmChainGrowthRate));//环比增长率
        result.put("current",  DateUtil.formatDate(startOfCurrentMonth, "yyyy-MM"));
        result.put("last",  DateUtil.formatDate(startOfLastMonth, "yyyy-MM"));
        
        return result;
    }
    
    @Override
    public Map<String, Object> getYearlyAlarmStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前年份的开始和结束时间
        Date today = new Date();
        Date startOfCurrentYear = DateUtil.getStartOfYear(today);
        Date endOfCurrentYear =  DateUtil.getEndOfYear(today);
        
        // 获取去年的开始和结束时间
        Date lastYear =  DateUtil.addYears(today, -1);
        Date startOfLastYear =  DateUtil.getStartOfYear(lastYear);
        Date endOfLastYear =  DateUtil.getEndOfYear(lastYear);
        
        // 当年报警数量
        QueryWrapper<AlarmRecordsEntity> currentYearAlarmQuery = new QueryWrapper<>();
        currentYearAlarmQuery.between("alarm_time", startOfCurrentYear, endOfCurrentYear);
        int currentYearAlarmCount = Math.toIntExact(baseMapper.selectCount(currentYearAlarmQuery));
        
        // 当年解决数量
        QueryWrapper<AlarmRecordsEntity> currentYearResolvedQuery = new QueryWrapper<>();
        currentYearResolvedQuery.between("alarm_time", startOfCurrentYear, endOfCurrentYear);
        currentYearResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int currentYearResolvedCount = Math.toIntExact(baseMapper.selectCount(currentYearResolvedQuery));
        
        // 去年报警数量
        QueryWrapper<AlarmRecordsEntity> lastYearAlarmQuery = new QueryWrapper<>();
        lastYearAlarmQuery.between("alarm_time", startOfLastYear, endOfLastYear);
        int lastYearAlarmCount = Math.toIntExact(baseMapper.selectCount(lastYearAlarmQuery));
        
        // 去年解决数量
        QueryWrapper<AlarmRecordsEntity> lastYearResolvedQuery = new QueryWrapper<>();
        lastYearResolvedQuery.between("alarm_time", startOfLastYear, endOfLastYear);
        lastYearResolvedQuery.eq("status", ALARTM_STATUS_ENUM.PROCESSED.getCode()); // 假设已解决的状态值为"resolved"
        int lastYearResolvedCount = Math.toIntExact(baseMapper.selectCount(lastYearResolvedQuery));
        
        // 计算年度报警环比增长率
        double yearlyAlarmChainGrowthRate = 0.0;
        if (lastYearAlarmCount != 0) {
            yearlyAlarmChainGrowthRate = ((double)(currentYearAlarmCount - lastYearAlarmCount) / lastYearAlarmCount) * 100;
        }
        // 将结果放入Map
        result.put("currentAlarmCount", currentYearAlarmCount);
        result.put("currentResolvedCount", currentYearResolvedCount);
        result.put("lastAlarmCount", lastYearAlarmCount);
        result.put("lastResolvedCount", lastYearResolvedCount);
        result.put("alarmChainGrowthRate", String.format("%.2f%%", yearlyAlarmChainGrowthRate));//环比增长率
        result.put("current",  DateUtil.formatDate(startOfCurrentYear, "yyyy"));
        result.put("last",  DateUtil.formatDate(startOfLastYear, "yyyy"));
        return result;
    }
    
    @Override
    public Map<String, Object> getAlarmLevelStatistics(Date startDate,Date endDate) {
        Map<String, Object> result = new HashMap<>();
        // 获取最近一个月的开始时间
        Date startOfLastMonth =startDate;
        Date endOfToday = endDate;
        
        // 查询最近一个月的报警记录，按报警等级分组统计
        QueryWrapper<AlarmRecordsEntity> queryWrapper = new QueryWrapper<>();
        if(startDate!=null&&endDate!=null)queryWrapper.between("alarm_time", startOfLastMonth, endOfToday);
        queryWrapper.select("alarm_level, COUNT(*) as count");
        queryWrapper.groupBy("alarm_level");
        List<Map<String, Object>> levelStats = baseMapper.selectMaps(queryWrapper);
        List<StatisticsPieVO> listStats=new ArrayList<StatisticsPieVO>();
        // 计算总报警数量
        int total = 0;
        for (Map<String, Object> stat : levelStats) {
        	String alarmLevel=(String) stat.get("alarm_level");
            Long count = (Long) stat.get("count");
            if (count != null) {
            	total += count.intValue();
            }
            StatisticsPieVO item=new StatisticsPieVO();
            item.setCount(count);
            item.setName(alarmLevel);
            listStats.add(item);
        }
        // 计算各等级报警占比
        for (StatisticsPieVO stat : listStats) {
            Long count =stat.getCount();
            if (count != null) {
            	  double percentage = total > 0 ? (count.doubleValue() / total) * 100 : 0.0;
                  stat.setPercentage(String.format("%.2f%%", percentage));
            }
        }
        // 将结果放入Map
        result.put("alarmLevelStats", listStats);
        result.put("totalAlarms", total);
        if(startDate!=null&&endDate!=null) result.put("period",  DateUtil.formatDate(startOfLastMonth, "yyyy-MM") + " 至 " +  DateUtil.formatDate(endDate, "yyyy-MM-dd"));
        return result;
    }
    
    @Override
    public Map<String, Object> getAlarmStatusStatistics(Date startDate,Date endDate) {
        Map<String, Object> result = new HashMap<>();
        // 获取最近一个月的开始时间
        Date startOfLastMonth =startDate;
        Date endOfToday =endDate;
        
        // 查询最近一个月的报警记录，按处理状态分组统计
        QueryWrapper<AlarmRecordsEntity> queryWrapper = new QueryWrapper<>();
        if(startDate!=null&&endDate!=null)queryWrapper.between("alarm_time", startOfLastMonth, endOfToday);
        queryWrapper.select("status, COUNT(*) as count");
        queryWrapper.groupBy("status");
        
        List<Map<String, Object>> statusStats = baseMapper.selectMaps(queryWrapper);
        // 计算各状态报警占比
        List<StatisticsPieVO> listStats=new ArrayList<StatisticsPieVO>();
        // 计算总报警数量
        int total = 0;
        for (Map<String, Object> stat : statusStats) {
        	Integer status = (Integer) stat.get("status");
            Long count = (Long) stat.get("count");
            if (count != null) {
            	total += count.intValue();
            }
            StatisticsPieVO item=new StatisticsPieVO();
            item.setCount(count);
            item.setState(status);
            item.setName(ALARTM_STATUS_ENUM.findByState(status).getDescription());
            listStats.add(item);
        }
        // 计算各等级报警占比
        for (StatisticsPieVO stat : listStats) {
            Long count =stat.getCount();
            if (count != null) {
            	  double percentage = total > 0 ? (count.doubleValue() / total) * 100 : 0.0;
                  stat.setPercentage(String.format("%.2f%%", percentage));
            }
        }
        // 将结果放入Map
        result.put("alarmStatusStats", listStats);
        result.put("totalAlarms", total);
        if(startDate!=null&&endDate!=null)result.put("period",  DateUtil.formatDate(startOfLastMonth, "yyyy-MM") + " 至 " +  DateUtil.formatDate(endDate, "yyyy-MM-dd"));
        return result;
    }
    @Override
    public Map<String, Object> getAlarmGroupStatistics(Date startDate,Date endDate,Integer timeType) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        // 获取最近一个月的开始时间
        params.put("confirmTimeStart", DateUtil.formatDateTime(startDate));
        params.put("confirmTimeEnd", DateUtil.formatDateTime(endDate));
        params.put("groupType", timeType);
        List<Map<String,Object>> levelStat=this.baseMapper.queryGroupLevelStat(params);
        List<Map<String,Object>> stateStat=this.baseMapper.queryGroupStateStat(params);
        // 将结果放入Map
        result.put("levelStat", levelStat);
        result.put("stateStat", stateStat);
        return result;
    }
}